import { Request, Response, NextFunction } from 'express';

const auth = async (req: Request, res: Response, next: NextFunction) => {
	const AUTH_SECRET_KEY = process.env.AUTH_SECRET_KEY;

	if (typeof AUTH_SECRET_KEY === 'string' && AUTH_SECRET_KEY.length > 0) {
		try {
			const authorization = req.header('Authorization');
			if (!authorization || authorization.replace('Bearer ', '').trim() !== AUTH_SECRET_KEY.trim()) {
				throw new Error('Error: 无访问权限 | No access rights');
			}
			next();
		} catch (error) {
			console.error('Authorization error:', error);
			res.status(401).send({
				status: 'Unauthorized',
				message: error.message ?? 'Please authenticate.',
				data: null
			});
		}
	} else {
		if (typeof AUTH_SECRET_KEY === 'undefined') {
			console.warn('Warning: AUTH_SECRET_KEY is not defined in environment variables.');
		}
		next();
	}
};

export { auth };

